package xiaoyang.controller.back;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.mysql.cj.util.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import xiaoyang.Constants;
import xiaoyang.pojo.AppInfo;
import xiaoyang.pojo.AppVersion;
import xiaoyang.pojo.DataDictionary;
import xiaoyang.pojo.Dev_user;
import xiaoyang.service.AppCategoryService;
import xiaoyang.service.AppInfoService;
import xiaoyang.service.DataDictionaryService;


import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/appInfo")
public class appInfoController {
    @Resource
    private AppInfoService appInfoService;
    @Resource
    private AppCategoryService appCategoryService;
    @Resource
    private DataDictionaryService dataDictionaryService;

 /*   @RequestMapping("/appInfoList")
    public Object appInfoList(@RequestParam(required = false,defaultValue = "")String softwareName,
                              @RequestParam(required = false,defaultValue = "0") String flatformId,
                              @RequestParam(required = false,defaultValue = "0") String categoryLevel1,
                              @RequestParam(required = false,defaultValue = "0") String categoryLevel2,
                              @RequestParam(required = false,defaultValue = "0") String categoryLevel3,
                              @RequestParam(required = false,defaultValue = "1")Integer pageNum,
                              @RequestParam(required = false,defaultValue = "5")Integer pageSize, Model model){
        if (pageNum<0){
            pageNum=1;
        }
        int totalCount=appInfoService.appInfoCount(softwareName,Integer.parseInt(flatformId),Integer.parseInt(categoryLevel1),Integer.parseInt(categoryLevel2),Integer.parseInt(categoryLevel3));
        int totalPage=totalCount%pageSize==0?(totalCount/pageSize):(totalCount/pageSize+1);
        List<AppInfo> appInfoList=appInfoService.getInfoAll(softwareName,Integer.parseInt(flatformId),Integer.parseInt(categoryLevel1),Integer.parseInt(categoryLevel2),Integer.parseInt(categoryLevel3),(pageNum-1)*pageSize,pageSize);
        List<DataDictionary> dictionary = dataDictionaryService.getDictionary();
        model.addAttribute("ddry", dictionary);
        model.addAttribute("appInfo", appInfoList);
        model.addAttribute("total",totalPage);
        model.addAttribute("totalCount",totalCount);
        model.addAttribute("pageIndex",pageNum);
        model.addAttribute("softwareName",softwareName);
        model.addAttribute("categoryLevel1",categoryLevel1);
        model.addAttribute("categoryLevel2",categoryLevel2);
        model.addAttribute("categoryLevel3",categoryLevel3);
        model.addAttribute("flatformId",flatformId);
        return "appInfoList";
    }*/
    @RequestMapping("devlist")
    public  Object tolist(){
        return "redirect:/appInfo/devappInfoList";
    }
    @RequestMapping("/devappInfoList")
    public Object appInfoList(@RequestParam(required = false,defaultValue = "")String softwareName,
                              @RequestParam(required = false,defaultValue = "0") String flatformId,
                              @RequestParam(required = false,defaultValue = "0") String status,
                              @RequestParam(required = false,defaultValue = "0") String categoryLevel1,
                              @RequestParam(required = false,defaultValue = "0") String categoryLevel2,
                              @RequestParam(required = false,defaultValue = "0") String categoryLevel3,
                              @RequestParam(required = false,defaultValue = "1")Integer pageNum,
                              @RequestParam(required = false,defaultValue = "5")Integer pageSize, Model model){

        PageInfo<AppInfo> pageInfo=appInfoService.getDevInfoAll(softwareName,Integer.parseInt(flatformId),Integer.parseInt(status),Integer.parseInt(categoryLevel1),Integer.parseInt(categoryLevel2),Integer.parseInt(categoryLevel3),pageNum,pageSize);
        List<DataDictionary> dictionary2 = dataDictionaryService.getStatus();
        List<DataDictionary> dictionary = dataDictionaryService.getDictionary();
        model.addAttribute("ddry", dictionary);
        model.addAttribute("ddry2", dictionary2);
        model.addAttribute("appInfo", pageInfo.getList());
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("pageIndex",pageNum);
        model.addAttribute("softwareName",softwareName);
        model.addAttribute("categoryLevel1",categoryLevel1);
        model.addAttribute("categoryLevel1v",Integer.parseInt(categoryLevel1));


        model.addAttribute("categoryLevel2",categoryLevel2);
        model.addAttribute("categoryLevel3",categoryLevel3);
        model.addAttribute("flatformId",flatformId);
        model.addAttribute("status",status);
        return "appInfoDev";
    }
    @RequestMapping("/APKNameExist")
    @ResponseBody
    public Object devAPKName(@RequestParam String APKName){
        HashMap<String ,String> map=new HashMap<String ,String>();

        if (StringUtils.isNullOrEmpty(APKName)){
           map.put("APKName","true");
        }else {
            AppInfo apkName = appInfoService.getApkName(APKName);
            if (apkName!=null){
                map.put("APKName","false");
            }else {
                map.put("APKName","true");

            }
        }
        return JSON.toJSONString(map);
    }
    @RequestMapping("/toadd")
    public String  toadd(Model model){
        List<DataDictionary> dictionary = dataDictionaryService.getDictionary();
        model.addAttribute("ddry",dictionary);
        return "devappInfoadd";
    }
    @PostMapping("/appInfoAdd")
    public Object appInfoAdd(AppInfo appInfo, HttpSession session, HttpServletRequest request, @RequestParam(value = "picPath",required = false) MultipartFile pic){
        String logoPicPath=null;
        String logoLocPath=null;
        boolean flag=true;
        String path=request.getSession().getServletContext().getRealPath("/statics/upload/");
        String path2=File.separator+"statics"+File.separator+"upload"+File.separator;
        String oldPic=pic.getOriginalFilename(); //源文件名
        String prefix= FilenameUtils.getExtension(oldPic);//原文件后缀名
        int fileSize=52428800;
        if (pic.getSize()>fileSize){
            request.setAttribute("uploadError","文件上传大小不得超过50Mb");
            return "devappInfoadd";
        }else if (prefix.equalsIgnoreCase("jpg")||prefix.equalsIgnoreCase("png")||prefix.equalsIgnoreCase("jpeg")){
            String fileName=System.currentTimeMillis()+ RandomUtils.nextInt(52428800)+"_Personal."+prefix;

            File targeFile=new File(path);
            if (!targeFile.exists()){
                targeFile.mkdirs();
            }
            try{
                pic.transferTo(new File(targeFile,fileName));
            }catch (Exception e){
                e.printStackTrace();
                request.setAttribute("uploadError","上传失败");
                return "devappInfoadd";
            }
            logoPicPath=path2+fileName;
            logoLocPath=path+fileName;

        }else {
            request.setAttribute("uploadError","文件上传格式不对");
            return "devappInfoadd";
        }
        Dev_user dev_user  = (Dev_user) session.getAttribute(Constants.DEV_USER_SESSION);
        appInfo.setCreatedBy(dev_user.getId());
        appInfo.setDevId(dev_user.getId());
        appInfo.setCreationDate(new Date());
        appInfo.setLogoPicPath(logoPicPath);
        appInfo.setLogoLocPath(logoLocPath);
        if (appInfoService.appInfoAdd(appInfo)){
            return "redirect:/appInfo/devappInfoList";
        }
        return "devappInfoadd";
    }
    @RequestMapping("/view/{id}")
    public Object view(@PathVariable Integer id,Model model){
        model.addAttribute("appView",appInfoService.getIdAll(id));
        List<DataDictionary> dictionary = dataDictionaryService.getDictionary();
        List<DataDictionary> status = dataDictionaryService.getStatus();
        model.addAttribute("ddry",dictionary);
        model.addAttribute("ddry2",status);

        return "devappInfoupdate";
    }
    @RequestMapping("/appInfoUpdate")
    public Object appInfoUpdate(@RequestParam Integer id,AppInfo appInfo,@RequestParam String logoPic
            ,@RequestParam String logoLoPic
            ,HttpSession session,HttpServletRequest request,@RequestParam(value = "picPath",required = false) MultipartFile pic){
        String logoPicPath=null;
        String logoLocPath=null;

        String path2=File.separator+"statics"+File.separator+"upload"+File.separator;
        String path=request.getSession().getServletContext().getRealPath("/statics/upload/");
            String oldPic=pic.getOriginalFilename(); //源文件名
            String prefix= FilenameUtils.getExtension(oldPic);//原文件后缀名
            int fileSize=52428800;
            if (pic.getSize()>fileSize){
                request.setAttribute("uploadError","文件上传大小不得超过50Mb");
                return "devappInfoupdate";
            }else if (prefix.equalsIgnoreCase("jpg")||prefix.equalsIgnoreCase("png")||prefix.equalsIgnoreCase("jpeg")){
                String fileName=System.currentTimeMillis()+ RandomUtils.nextInt(52428800)+"_Personal."+prefix;

                File targeFile=new File(path);
                if (!targeFile.exists()){
                    targeFile.mkdirs();
                }
                try{
                    pic.transferTo(new File(targeFile,fileName));
                }catch (Exception e){
                    e.printStackTrace();
                    request.setAttribute("uploadError","上传失败");
                    return "devappInfoupdate";
                }
                logoPicPath=path2+fileName;
                logoLocPath=path+fileName;

            }else {
                request.setAttribute("uploadError","文件上传格式不对");
                return "devappInfoupdate";
            }

            Dev_user dev_user  = (Dev_user) session.getAttribute(Constants.DEV_USER_SESSION);

            appInfo.setModifyBy(dev_user.getId());
            appInfo.setId(id);
            appInfo.setModifyDate(new Date());
            appInfo.setLogoPicPath(logoPicPath);
            appInfo.setLogoLocPath(logoLocPath);
            if (appInfoService.update(appInfo)){
                return "redirect:/appInfo/devappInfoList";

        }
        return "devappInfoupdate";
    }
    @RequestMapping("/toversion/{appId}")
    public Object toversion(@PathVariable Integer appId,Model model){
      List<AppVersion> appVersions=null;
        try {
            appVersions= appInfoService.getVersion(appId);
        }catch (Exception e){
            e.printStackTrace();
        }
        model.addAttribute("appIdd",appId);
        model.addAttribute("version",appVersions);
        return "versionadd";
    }
    @RequestMapping("/toupVer/{appId}/{versionId}/{downloads}")
    public Object toupVer(@PathVariable Integer appId,@PathVariable Integer versionId,@PathVariable Integer downloads,Model model){
        List<AppVersion> versionList = appInfoService.getVersion(appId);
        try{
            AppVersion appVersion = appInfoService.appVersionId(versionId);
            model.addAttribute("version",appVersion);
        }catch (Exception e){
            e.printStackTrace();
        }

        model.addAttribute("downloads",downloads);
        model.addAttribute("appIdd",appId);
        model.addAttribute("versionList",versionList);

        return "versionupdate";
    }
    @PostMapping("/addVersion")
    public Object addVersion(AppVersion appVersion ,@RequestParam String versionNo,HttpServletRequest request,@RequestParam(required = false,value = "download")MultipartFile downPic,HttpSession session){
       String appId = request.getParameter("appId");
        String downloadLink=null;
        String apkLocPath=null;
        String apkFileName=null;
        AppInfo appInfo=new AppInfo();
        String path=request.getSession().getServletContext().getRealPath("/statics/upload/");

        String oldPicName=downPic.getOriginalFilename();
        String prefix= FilenameUtils.getExtension(oldPicName);

        int picSize=524288000;
        if (downPic.getSize()>picSize){
            request.setAttribute("uploadError","文件上传大小不得超过50Mb");
            return "versionadd";
        }else if (prefix.equalsIgnoreCase("apk")){
             apkFileName=System.currentTimeMillis()+ RandomUtils.nextInt(52428800)+"_Personal."+versionNo+"."+prefix;

            File targeFile=new File(path);
            if (!targeFile.exists()){
                targeFile.mkdirs();
            }
            try{
                downPic.transferTo(new File(targeFile,apkFileName));
            }catch (Exception e){
                e.printStackTrace();
                request.setAttribute("uploadError","上传失败");
                return "versionadd";
            }
            apkLocPath=path+apkFileName;
            downloadLink=File.separator+"statics"+File.separator+"upload"+File.separator+apkFileName;

        }else {
            request.setAttribute("uploadError","文件上传格式不对");
            return "versionadd";
        }
        Dev_user dev_user  = (Dev_user) session.getAttribute(Constants.DEV_USER_SESSION);
        appVersion.setDownloadLink(downloadLink);
        appVersion.setCreatedBy(dev_user.getId());
        appVersion.setCreationDate(new Date());
        appVersion.setApkLocPath(apkLocPath);
        appVersion.setApkFileName(apkFileName);
        appVersion.setAppId(Integer.parseInt(appId));
        if (appInfoService.versionAdd(appVersion)){
            appInfo.setVersionId(appVersion.getId());
            appInfo.setId(Integer.parseInt(appId));
            if (appInfoService.updateVersion(appInfo)){
                return "redirect:/appInfo/devappInfoList";
            }
            return "versionadd";

        }
        return "versionadd";
    }
    @RequestMapping("/upAppVersion")
    public Object upAppVersion(AppVersion appVersion ,@RequestParam String versionNo,HttpServletRequest request,@RequestParam(required = false,value = "download")MultipartFile downPic,HttpSession session){
        String downloadLink=null;
        String apkLocPath=null;
        String apkFileName=null;
        AppInfo appInfo=new AppInfo();
        String path=request.getSession().getServletContext().getRealPath("/statics/upload/");
        String oldPicName=downPic.getOriginalFilename();
        String prefix= FilenameUtils.getExtension(oldPicName);

        int picSize=524288000;
        if (downPic.getSize()>picSize){
            request.setAttribute("uploadError","文件上传大小不得超过50Mb");
            return "versionadd";
        }else if (prefix.equalsIgnoreCase("apk")){
            apkFileName=System.currentTimeMillis()+ RandomUtils.nextInt(52428800)+"_Personal."+versionNo+"."+prefix;

            File targeFile=new File(path);
            if (!targeFile.exists()){
                targeFile.mkdirs();
            }
            try{
                downPic.transferTo(new File(targeFile,apkFileName));
            }catch (Exception e){
                e.printStackTrace();
                request.setAttribute("uploadError","上传失败");
                return "versionadd";
            }
            apkLocPath=path+apkFileName;
            downloadLink=File.separator+"statics"+File.separator+"upload"+File.separator+apkFileName;

        }else {
            request.setAttribute("uploadError","文件上传格式不对");
            return "versionadd";
        }
        Dev_user dev_user  = (Dev_user) session.getAttribute(Constants.DEV_USER_SESSION);
        appVersion.setModifyBy(dev_user.getId());
        appVersion.setDownloadLink(downloadLink);
        appVersion.setModifyDate(new Date());
        appVersion.setApkLocPath(apkLocPath);
        appVersion.setApkFileName(apkFileName);
        if (appInfoService.upVersion(appVersion)){
            return "redirect:/appInfo/devappInfoList";
        }
        return "versionupdate";
    }
    @RequestMapping("/devView/{appId}")
    public Object devView(@PathVariable Integer appId,Model model){
        AppInfo appInfoId = appInfoService.getAppInfoId(appId);
        List<AppVersion> version = appInfoService.getVersion(appId);
        model.addAttribute("appView",appInfoId);
        model.addAttribute("version",version);

        return "devView";
    }
    @RequestMapping("/devDel/{id}")
    public Object devDel(@PathVariable Integer id,HttpServletRequest request) throws Exception {
        boolean flag=false;
        AppInfo appInfo=appInfoService.getAppInfoId(id);
        int count=appInfoService.appIdCount(id);
        if(count!=0){
            for (AppVersion appVersion : appInfoService.getVersion(id)) {
                if (appVersion.getApkLocPath()!=null&&!appVersion.getApkLocPath().equals("")){
                    File file=new File(appVersion.getApkLocPath());
                    file.delete();
                }
            }
            appInfoService.verDel(id);

                File file=new File(appInfo.getLogoPicPath());
                file.delete();

            if (appInfoService.devDel(id)){
                return "redirect:/appInfo/devappInfoList";
            }
        }else {
            if (appInfo.getLogoPicPath()!=null&&!appInfo.getLogoPicPath().equals("")){
                File file =new File(appInfo.getLogoPicPath());
                    file.delete();
            }
            if (appInfoService.devDel(id)){
                return "redirect:/appInfo/devappInfoList";
            }
        }

        return "appInfoDev";
    }
    @RequestMapping("/xj/{id}")
    public Object xj(@PathVariable Integer id){
        if (appInfoService.xj(id)){
            return "redirect:/appInfo/devappInfoList";
        }
        return "appInfoDev";
    }
    @RequestMapping("/sj/{id}")
    public Object sj(@PathVariable Integer id){
        if (appInfoService.sj(id)){
            return "redirect:/appInfo/devappInfoList";
        }
        return "appInfoDev";
    }
        /*HashMap hashMap=new HashMap();
        if (appInfoService.sj(id)){
           hashMap.put("sjj","true");
        }else{
            hashMap.put("sjj","false");
        }
        return JSON.toJSONString(hashMap);
    }*/
/*    @RequestMapping("/auditView/{id}/{versionId}")
    public Object auditView(@PathVariable Integer id,@PathVariable Integer versionId,Model model){
        AppInfo idAll = appInfoService.getAppInfoId(id);
        AppVersion appVersion = appInfoService.appVersionId(versionId);
        model.addAttribute("appView",idAll);
        model.addAttribute("version",appVersion);
        return "audit";
    }
    @RequestMapping("/auditPass/{id}")
    public Object auditPass(@PathVariable Integer id){
        if (appInfoService.auditPass(id)){
            return "redirect:/appInfo/appInfoList";
        }
        return "appInfoList";
    }
    @RequestMapping("/auditNoPass/{id}")
    public Object auditNoPass(@PathVariable Integer id){
        if (appInfoService.auditNoPass(id)){
            return "redirect:/appInfo/appInfoList";
        }
        return "appInfoList";
    }*/
    @RequestMapping("/download/{fileName}/{id}")
    public void upload(@PathVariable String fileName, @PathVariable Integer id, HttpServletResponse response, HttpServletRequest request) throws IOException, IOException {
        appInfoService.updateDownloads(id);
        String realPath = request.getServletContext().getRealPath("statics" + File.separator + "upload");
        FileInputStream inputStream = new FileInputStream(realPath+File.separator+fileName);
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] bytes = fileName.getBytes("UTF-8");
        fileName = new String(bytes, "ISO-8859-1");
        response.setHeader("Content-Disposition", "attachment;filename="+fileName);
        IOUtils.copy(inputStream, outputStream);
    }
    @ResponseBody
    @RequestMapping("/delImg/{id}")
    public Object delImg(@PathVariable Integer id){
        AppInfo appInfoId = appInfoService.getAppInfoId(id);
        String LogoLocPath=appInfoId.getLogoLocPath();
        if (appInfoService.upImg(id)){
            File file=new File(LogoLocPath);
            file.delete();
            return "true";
        }
        return "false";
    }
    @ResponseBody
    @RequestMapping("/delApk/{id}")
    public Object delApk(@PathVariable Integer id){
        AppVersion appVersion = appInfoService.appVersionId(id);
        String apkLocPath=appVersion.getApkLocPath();
        if (appInfoService.upApk(id)){
            File file=new File(apkLocPath);
            file.delete();
            return "true";
        }
        return "false";
    }
}
